﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Thread = System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Infrastucture;
using Infrastucture.Collections;
using TimeSplicerModule.Factories;
using TimeSplicerModule.DomainModels;
using TimeSplicerModule.Security;
using TimeSplicerModule.ViewModels;


namespace TimeSplicerModule.Services
{
    public partial class ProjectService : IProjectService
    {
        public int MyProjectCount(StatusModel byStatus)
        {


            return GetMyProjects(byStatus).Count;
        }

        public int MyActiveProjectCount()
        {
            _session = _container.Resolve<ISession>();

            var statuses = _session.Statuses; //_statusFactory.GetList();
            var notStarted = statuses.FirstOrDefault(x => x.Status == Status.Not_Started);
            var active = statuses.FirstOrDefault(x => x.Status == Status.Active);

            var projects = GetMyProjects().Where(x => x.StatusGuid == notStarted.StatusGuid
                || x.StatusGuid == active.StatusGuid).ToList();


            return projects.Count;
        }
        


        public double ProjectHours(Guid projectGuid)
        {
            var tasks = _taskFactory.GetList(x => x.ProjectGuid == projectGuid);

            return getProjectHours(tasks);
        }

        public double ProjectHours(List<TaskModel> tasks)
        {
            return getProjectHours(tasks);
        }


        private double getProjectHours(List<TaskModel> tasks)
        {
            double hours = 0D;

            var timestamps = _timestampFactory.GetList();

            foreach (var t in tasks)
            {
                t.Timestamps = timestamps.Where(x => x.TaskGuid == t.TaskGuid).ToList();

                if (t.Timestamps != null && t.Timestamps.Count > 0)
                    hours += getTaskHours(t.Timestamps);
            }



            return Math.Round(hours, 2);
        }

        private double getTaskHours(List<TimestampModel> timestamps)
        {
            double hours = 0D;

            foreach (var t in timestamps)
            {
                hours += t.Hours;
            }

            return Math.Round(hours, 2);
        }
    }
}
